package abaco.symbol.operation;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import abaco.Symbol;
import abaco.gui.Panel;
import abaco.symbol.Operation;
import abaco.symbol.Text;

public abstract class Boundered extends Operation {
	public static final String BOUND_UPPER = "operation-boundered-upper";
	public static final String BOUND_LOWER = "operation-boundered-lower";
	public static final String EQUATION = "operation-boundered-equation";

	protected String latexOperator;

	public Boundered() {
		setSymbolChild(new Text(), BOUND_UPPER);
		setSymbolChild(new Text(), BOUND_LOWER);
		setSymbolChild(new Text(), EQUATION);
	}

	@Override
	public Symbol buildPanel(Panel panel) {
		panel.setLayout(new GridBagLayout());

		// bound upper
		Panel upperPanel = getChildPanel(BOUND_UPPER, true);
		GridBagConstraints upperConstraints = new GridBagConstraints();
		upperConstraints.gridx = 0;
		upperConstraints.gridy = 0;
		panel.add(upperPanel, upperConstraints);

		// equation
		Panel equationPanel = getChildPanel(EQUATION, false);
		GridBagConstraints equationConstraints = new GridBagConstraints();
		equationConstraints.gridx = 1;
		equationConstraints.gridy = 1;
		equationConstraints.insets = new Insets(-5, 0, -5, 0);
		panel.add(equationPanel, equationConstraints);

		// bound lower
		Panel lowerPanel = getChildPanel(BOUND_LOWER, true);
		GridBagConstraints lowerConstraints = new GridBagConstraints();
		lowerConstraints.gridx = 0;
		lowerConstraints.gridy = 2;
		panel.add(lowerPanel, lowerConstraints);

		return this;
	}

	@Override
	public String toLatex() {
		StringBuilder latex = new StringBuilder();
		latex.append("{");
		latex.append(null == latexOperator ? UNDEFINED_LATEX : latexOperator);
		String lower = toLatex(BOUND_LOWER);
		if (!lower.equals(UNDEFINED_LATEX)) {
			latex.append("_");
			latex.append(lower);
		}
		String upper = toLatex(BOUND_UPPER);
		if (!upper.equals(UNDEFINED_LATEX)) {
			latex.append("^");
			latex.append(upper);
		}
		latex.append(toLatex(EQUATION));
		latex.append("}");
		return latex.toString();
	}
}
